//
//  KQConversationListViewController.swift
//  JChat
//
//  Created by JIGUANG on 2017/2/16.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import KQSearch
import KQEmptyView
import KQChatSDK

open class KQConversationListViewController: KQChatBaseViewController, KQSearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
    
    /// 会话列表
//    public var datas: [JMSGConversation] = []
    /// 是否正在连接
//    public var isConnecting = false
    /// 网络异常提示
    public lazy var errorTips: KQNetworkTipsCell = KQNetworkTipsCell()
    /// 是否展示网络异常提示
    public var showNetworkTips = false
    
    private var conversations: [WFCCConversationInfo] = []
    private var firstAppear: Bool = true
    private var isSearchConversationListExpansion: Bool?
    
    // MARK: - life cycle
    required public init(shouldInit: Bool) {
        super.init(nibName: nil, bundle: nil)
        if shouldInit == true {
            self._init()
        }
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "消息"
        
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
//        if isConnecting {
//            titleTips.text = "连接中"
//            titleTipsView.isHidden = false
//        } else {
//            titleTipsView.isHidden = true
//        }
        
        /// todo
        
        self.updateTitle()
        self.refreshList()
    }
    
    open override func viewWillDisappear(_ animated: Bool) {
        titleTipsView.isHidden = true
    
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
        
    }
    
    // MARK: - UI
    private func _init() {
        self.navigationItem.title = "消息"
        view.backgroundColor = KQCHAT_BG_COLOR

        let appDelegate = UIApplication.shared.delegate
        let window = appDelegate?.window!
        window?.addSubview(titleTipsView)
        
        view.addSubview(conversationTableView)
        view.addSubview(searchBar)
        self.addConstraints()
        
        //空白提示
        conversationTableView.ly_emptyView = KQEmptyView.kq_emptyView(withTitle: "暂无消息")
    
        /// tudo
        self.addNotifation()
        
    }
    // MARK: - AddNotifation
    
    func addNotifation() {
        NotificationCenter.default.addObserver(self, selector: #selector(onUserInfoUpdated(_:)), name: Notification.Name.init(rawValue: kUserInfoUpdated), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onSendingMessageStatusUpdated(_:)), name: Notification.Name.init(rawValue: kSendingMessageStatusUpdated), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onConnectionStatusChanged(_:)), name: Notification.Name.init(rawValue: kConnectionStatusChanged), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onReceiveMessages(_:)), name: Notification.Name.init(rawValue: kReceiveMessages), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onDeleteMessages(_:)), name: Notification.Name.init(rawValue: kDeleteMessages), object: nil)
        /// 网络
        NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: NSNotification.Name(rawValue: "kNetworkReachabilityChangedNotification"), object: nil)
    }
    
    /// 增加约束
    func addConstraints () {
        searchBar.snp.makeConstraints { (make) in
            if #available(iOS 11.0, *) {
                make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            } else {
                make.top.equalTo(self.topLayoutGuide.snp.top).offset(20)
            }
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(44)
        }
        conversationTableView.snp.makeConstraints { (make) in
            make.top.equalTo(self.searchBar.snp_bottom)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalTo(0)
        }
    }
    
    
    /// todo
    func refreshList() {
        self.conversations.removeAll()
        self.conversations.append(contentsOf: WFCCIMService.sharedWFCIM().getConversationInfos([0], lines: [0]))
        self.conversationTableView.reloadData()
    }
    
    func updateTitle() {
        let status = WFCCNetworkService.sharedInstance().currentConnectionStatus
        if status != .connecting && status != .receiving {
            switch status {
            case .logout:
                self.title = "未登录"
            case .connected:
                var count = 0
                self.conversations.forEach { info in
                    if !info.isSilent {
                        count += Int(info.unreadCount.unread)
                    }
                }
                self.title = "消息"
            case .unconnected:
                self.title = "未连接"
    
            default: break
                
            }
        } else {
            if status == .connecting {
                self.title = "连接中...";
            } else {
                self.title = "同步中...";
            }
        }
    }
    
    
    // MARK: - 通知
    /// 网络变化
    @objc func reachabilityChanged(note: NSNotification) {
        if let curReach = note.object as? Reachability {
            let status = curReach.currentReachabilityStatus()
            switch status {
            case NotReachable:
                notReachable()
            default :
                reachable()
            }
        }
    }
 
    /// todo
    @objc func onConnectionStatusChanged(_ noti: NSNotification) {
        self.updateTitle()
//        for i in 0..<conversations.count {
//            let conv = conversations[i]
//            if conv.conversation.type == WFCCConversationType.Single_Type && conv.conversation.target == userInfo.userId {
//                self.conversationTableView.reloadRows(at: [IndexPath.init(row: i, section: 0)], with: .fade)
//            } else if conv?.lastMessage.fromUser == userInfo.userId {
//                self.conversationTableView.reloadRows(at: [IndexPath.init(row: i, section: 0)], with: .fade)
//            }
//        }
        
        
    }
    @objc func onUserInfoUpdated(_ noti: NSNotification) {
        let userInfo: WFCCUserInfo = noti.userInfo?["userInfo"] as! WFCCUserInfo
        let dataSource = self.conversations
//        for i in 0..<conversations.count {
//            let conv = dataSource[i]
//            if conv.conversation.type == WFCCConversationType.Single_Type && conv?.conversation.target == userInfo.userId {
//                self.conversationTableView.reloadRows(at: [IndexPath.init(row: i, section: 0)], with: .fade)
//            } else if conv?.lastMessage.fromUser == userInfo.userId {
//                self.conversationTableView.reloadRows(at: [IndexPath.init(row: i, section: 0)], with: .fade)
//            }
//        }
        
        
    }
    @objc func onSendingMessageStatusUpdated(_ noti: NSNotification) {
        let messageId: Int = noti.object as! Int
        let dataSource = self.conversations
        if messageId == 0 {
            return
        }
//        for i in 0..<(dataSource?.count ?? 0) {
//            let conv = dataSource?[i]
//            if conv?.lastMessage != nil {
//                if (conv?.lastMessage.direction == .MessageDirection_Send && conv?.lastMessage.messageId == messageId) {
//                    self.conversationTableView.reloadRows(at: [IndexPath.init(row: i, section: 0)], with: .fade)
//                }
//            }
//
//        }
    }
    
    @objc func onReceiveMessages(_ noti: NSNotification) {
        let messages: [WFCCMessage] = noti.object as? [WFCCMessage] ?? []
        if messages.count > 0 {
            // 刷新
            self.refreshList()
        }
    }
    
    
    @objc func onDeleteMessages(_ noti: NSNotification) {
        // 刷新
        self.refreshList()
    }
    
    // MARK: - UITableViewDataSource
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == self.searchBar.searchResultTableView {
            //搜索
            return self.searchConversationList.count
        }
        return showNetworkTips ? conversations.count + 1 : conversations.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if tableView == self.searchBar.searchResultTableView {
            //搜索
            let cell = tableView.dequeueReusableCell(withIdentifier: "KQConversationCell", for: indexPath) as! KQConversationCell
            cell.bindSearchConversation(self.searchConversationList[indexPath.row])
            return cell
        } else {
            if showNetworkTips && indexPath.row == 0 {
                errorTips.selectionStyle = .none
                return errorTips
            }
            let cell = tableView.dequeueReusableCell(withIdentifier: "KQConversationCell", for: indexPath) as! KQConversationCell
            cell.bindConversation(self.conversations[indexPath.row])
            return cell
        }
        
    }
    
    // MARK: - UITableViewDelegate
    public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let cell = cell as? KQConversationCell else {
            return
        }
        if tableView == self.searchBar.searchResultTableView {
        } else {
            
            cell.bindConversation(self.conversations[showNetworkTips ? indexPath.row - 1 : indexPath.row])
        }
        
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if tableView == self.searchBar.searchResultTableView {
            //搜索
            return 65
        }
        
        if showNetworkTips && indexPath.row == 0 {
            return 40
        }
        return 65
    }
    
    public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if showNetworkTips && indexPath.row == 0 {
            return
        }
        
        guard let _ = tableView.cellForRow(at: indexPath) as? KQConversationCell else {
            return
        }
        let vc = KQChatViewController()
        if tableView == self.searchBar.searchResultTableView {
            
            //搜索
            let conversation = self.searchConversationList[indexPath.row]

            guard let conversa = WFCCIMService.sharedWFCIM().getConversationInfo(conversation.conversation) else {
                return
            }
            vc.conversation = conversa

            
        } else {
            let conversation = conversations[showNetworkTips ? indexPath.row - 1:indexPath.row]
            vc.conversation = conversation
        }
        
        vc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(vc, animated: true)
    }
    
    public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    public func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let action1 = UITableViewRowAction(style: .destructive, title: "删除") { (action, indexPath) in
            self._delete(indexPath)
        }
        let conversation = conversations[showNetworkTips ? indexPath.row - 1 : indexPath.row]
        let action2 = UITableViewRowAction(style: .normal, title: "置顶") { (action, indexPath) in
            WFCCIMService.sharedWFCIM().setConversation(conversation.conversation, top: !conversation.isTop) {
                self.refreshList()
            } error: { error in
                self.refreshList()
            }
        }
        if conversation.isTop {
            action2.title = "取消置顶"
        } else {
            action2.title = "置顶"
        }
        return [action1, action2]
    }

    
    // MARK: - KQSearchBarDelegate
    open func searchBar(shouldBecomeActive searchBar: KQSearchBar) -> Bool {
        return true
    }
    open func searchBar(_ searchBar: KQSearchBar, textDidChange searchText: String?, complete: @escaping (Bool) -> Void) {
        
        self.searchConversationList = WFCCIMService.sharedWFCIM().searchConversation(searchText, inConversation: [NSNumber(value: WFCCConversationType.Single_Type.rawValue)], lines: [0])
        self.searchBar.searchResultTableView.reloadData()
        complete(false)
    }

    open func searchBar(_ searchBar: KQSearchBar, searchMore searchText: String?, complete: @escaping (Bool) -> Void) {
        complete(false)
    }

    /// 删除会话
    private func _delete(_ indexPath: IndexPath) {
        let conversation = conversations[indexPath.row]
        
        WFCCIMService.sharedWFCIM().clearUnreadStatus(conversation.conversation)
        WFCCIMService.sharedWFCIM().remove(conversation.conversation, clearMessage: true)
        
        self.conversations.remove(at: indexPath.row)
        
        self.conversationTableView.deleteRows(at: [indexPath], with: .fade)

        self.conversationTableView.ly_endLoading()
    }
    
    /// 网络可用
    func reachable() {
        if !showNetworkTips {
            return
        }
        showNetworkTips = false
        self.conversationTableView.reloadData()
    }
    
    /// 网络不可用
    func notReachable() {
        if showNetworkTips {
            return
        }
        showNetworkTips = true
        if conversations.count > 0 {
            let indexPath = IndexPath(row: 0, section: 0)
            self.conversationTableView.beginUpdates()
            conversationTableView.insertRows(at: [indexPath], with: .automatic)
            conversationTableView.endUpdates()
        } else {
            conversationTableView.reloadData()
        }
    }
    
    // MARK: - method
    
    
 
    
    // MARK: - lazy loading
    /// 会话TableView
    public lazy var conversationTableView: UITableView = {
        var conversationTableView = UITableView.init(frame: CGRect(x: 0, y: 37, width: KQCHAT_SCREEN_WIDTH, height: KQCHAT_SCREEN_HEIGHT-KQCHAT_SAFE_AREA_TOP_HEIGHT-37-KQCHAT_SAFE_AREA_BOTTOM_HEIGHT-49), style: .grouped)
        conversationTableView.delegate = self
        conversationTableView.dataSource = self
        conversationTableView.register(KQConversationCell.self, forCellReuseIdentifier: "KQConversationCell")
        conversationTableView.estimatedRowHeight = 0
        conversationTableView.estimatedSectionFooterHeight = 0
        conversationTableView.estimatedSectionFooterHeight = 0
        conversationTableView.separatorStyle = .none
        conversationTableView.backgroundColor = KQCHAT_BG_COLOR
        if #available(iOS 11.0, *) {
            conversationTableView.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
            self.automaticallyAdjustsScrollViewInsets = false
        }
        return conversationTableView
    }()
    
    /// 连接提示文本
    public lazy var titleTips: UILabel = {
        var tips = UILabel(frame: CGRect(x: 23, y: 0, width: 67, height: 44))
        tips.font = UIFont(name: KQCHAT_FONT_NAME, size: 18)
        tips.textColor = UIColor.white
        tips.textAlignment = .left
        tips.backgroundColor = UIColor(netHex: 0x5AD4D3)
        return tips
    }()

    /// 连接提示
    public lazy var titleTipsView: UIView = {
        var view = UIView(frame: CGRect(x: (self.view.width - 195) / 2 - 5, y: KQCHAT_STATUS_HEIGHT, width: 90, height: 44))
        view.backgroundColor = .clear
        let activityView = UIActivityIndicatorView(frame: CGRect(x: 0, y: 10, width: 20, height: 20))
        activityView.isUserInteractionEnabled = false
        view.addSubview(activityView)
        activityView.startAnimating()
        view.addSubview(self.titleTips)
        view.isHidden = true
        view.isUserInteractionEnabled = false
        return view
    }()
    
    /// 搜索
    public lazy var searchBar: KQSearchBar = {
        let searchBar: KQSearchBar = KQSearchBar(frame: CGRect(x: 0, y: 0, width: KQCHAT_SCREEN_WIDTH, height: 37))
        searchBar.backgroundColor = UIColor.white
        searchBar.delegate = self
        searchBar.textField.placeholder = "搜索"
        searchBar.searchBarContainer.backgroundColor = KQCHAT_BG_COLOR
        searchBar.searchResultTableView.backgroundColor = KQCHAT_BG_COLOR
        searchBar.searchBarContainerRect = KQSearchBar.viewRectMake(left: 12, right: 12, bottom: 7, height: 30)
        searchBar.searchResultTableView.register(KQConversationCell.self, forCellReuseIdentifier: "KQConversationCell")
        searchBar.line.isHidden = true
        return searchBar
    }()
    
 
    
    public lazy var searchConversationList: [WFCCConversationSearchInfo] = {
        let searchConversationList: [WFCCConversationSearchInfo] = [WFCCConversationSearchInfo]()
        return searchConversationList
    }()
    
}

